from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.forms import StartGroupForm
from StartGroup.forms import StartGroupFormNoMember
from contifyuser.models import Member
from django.contrib.auth.models import User
from StartGroup.models import Group
from groupMembers.models import Member_Group
from groupevents.models  import Events
import Constants
import connectpeople.Constants
from datetime import datetime
import simplejson
from django.http import HttpResponse
import utils.signals

# render form for starting a new group
def startNewGroupForm(request):
    
    render_template = Constants.start_group
    
    # Get User id from session
    if connectpeople.Constants.session_userid in request.session:
        # user is signed in
        userid = request.session[connectpeople.Constants.session_userid]
        user_info = getUserInfo(userid)
        member = getMemberInfo(user_info)
        # Start Group form initialization
        start_group_form = StartGroupForm()
        signin_form = ''
        render_template += Constants.group_form_authenticated_template
        
    else:
        # User is not signed in
        member = ''
        # Start Group form initialization
        start_group_form = StartGroupFormNoMember()
        signin_form = AuthenticationForm()
        render_template += Constants.group_form_not_authenticated_template
    
    # Send response
    return render_to_response(render_template,
                              {Constants.start_group_form_constant: start_group_form,
                                connectpeople.Constants.signin_form_constant: signin_form,
                                Constants.member_constant: member},
                              context_instance = RequestContext(request))
    
def startNewGroup(request):
    
    # Form validation flag
    form_validated = False
    
    render_template = Constants.start_group
    
    if connectpeople.Constants.session_userid in request.session:
        # User is signed in
        userid = request.session[connectpeople.Constants.session_userid]
        user_info = getUserInfo(userid)
        member = getMemberInfo(user_info)
        
        if request.method == 'POST':            
            # Start Group Authenticated form initialization
            start_group_form = StartGroupForm(data=request.POST)
            
            if start_group_form.is_valid():
                form_validated = True
                
                #Email parameters
                # Get email ids of these users
                recipient = User.objects.filter(username=userid).values_list('email', flat=True)
                # Compose subject for the email
                subj = request.POST.__getitem__('group_name') +  " - New ConnectPeople Group Created"
                # name of the recipeint
                rec_name = member.first_name
                
                start_group_form.save(member)

                utils.signals.send_single_mail.send(
                   sender=Group, email=recipient, name=rec_name, model=request.POST, subject=subj, template="email/newGroupEmail.html")
            else:
                # If form is not valid then redirect to same page
                render_template += Constants.group_form_authenticated_template
                signin_form = ''
    else:
        # User is not signed in
        member = ''
        if request.method == 'POST':
            # Start Group form initialization
            start_group_form = StartGroupFormNoMember(data=request.POST)
            
            if start_group_form.is_valid():
                form_validated = True
                
                #Email parameters
                # Get email ids of these users
                recipient = []
                recipient = recipient.append(request.POST.__getitem__('email'))
                print request.POST
                # Compose subject for the email
                subj = request.POST.__getitem__('group_name') +  " - New ConnectPeople Group Created"
                # name of the recipeint
                rec_name = request.POST.__getitem__('first_name')
                
                start_group_form.save()

                utils.signals.send_single_mail.send(
                   sender=Group, email=recipient, name=rec_name, model=request.POST, subject=subj, template="email/newGroupEmail.html")
                
                
            else:
                # If form is not valid then redirect to same page
                render_template += Constants.group_form_not_authenticated_template
                
                # If user is not signed in then show sign_in form
                signin_form = AuthenticationForm()
        
    if form_validated:
        render_template += Constants.group_registered_template
        return render_to_response(render_template,
                              {Constants.start_group_form_constant: start_group_form,
                                Constants.member_constant: member},
                              context_instance = RequestContext(request))
    else:
        return render_to_response(render_template,
                              {Constants.start_group_form_constant: start_group_form,
                                connectpeople.Constants.signin_form_constant: signin_form,
                                Constants.member_constant: member},
                              context_instance = RequestContext(request))
    
def group_view(request, group_web_address):
    
    if 'event_id' in request.session:
        # delete event id from session
        del request.session['event_id']

    if request.method == 'POST':
        # Get the comment id to be deleted
        eveid = request.POST.__getitem__('eveid')
            
        if eveid:
            # Delete the event from database
            Events.objects.get(id=eveid).delete()
            # Set response to success
            response = simplejson.dumps({'success':'success'})
            
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
                
    # Store group in session:
    request.session[connectpeople.Constants.session_group_web_address] = group_web_address
    group = getGroupFromWebAddr(group_web_address)
    # Upcoming group events list
    up_group_events = getEvents(group, Constants.up_group_events)
    up_group_event_list = getEventsInList(up_group_events)
    
    # Previous group events list
    prev_group_events = getEvents(group, Constants.prev_group_events)
    prev_group_event_list = getEventsInList(prev_group_events)
    
    # Obtain user
    userid = request.session[connectpeople.Constants.session_userid]
    user_info = getUserInfo(userid)
    
    # Prepare sub list of group members
    # Get user ids of all users associated with the group
    grp_mem_usrid = getGroupMembersUserIds(group)
    # Get email ids of these users
    usr_list = User.objects.filter(username__in=grp_mem_usrid)
    mem_list = Member.objects.filter(user__in=usr_list)[:5]
                
    # Check if user is already member of group
    isJoined= False    
    for each in grp_mem_usrid:
        if(each == userid):
            isJoined = True    
    
    return render_to_response(Constants.start_group + Constants.group_home_template,
                              {Constants.group_constant: group, 'up_group_event_list': up_group_event_list,
                               'prev_group_event_list': prev_group_event_list, 'isJoined': isJoined,
                               'mem_list': mem_list},
                              context_instance = RequestContext(request))


# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)

# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)
    
# Helper function to obtain grou info from group web address
def getGroupFromWebAddr(group_web_addr):
    return Group.objects.get(group_web_address=group_web_addr)


# Helper function to obtain Events associated with the group
def getEvents(group_info, date_filter):
    
    if date_filter == Constants.up_group_events:
        return Events.objects.filter(group=group_info).filter(event_date__gt = datetime.now()).order_by('-event_date')
    elif date_filter == Constants.prev_group_events:
        return Events.objects.filter(group=group_info).filter(event_date__lte = datetime.now()).order_by('-event_date')
    else:
        return Events.objects.filter(group=group_info)

# Helper function to obtain Events in a list format
def getEventsInList(group_events):
    group_event_list = []
    if group_events is not None:
        for each in group_events:
            group_event_list.append(each)
    
    return group_event_list

# Get All the members associated with the group
def getGroupMembersUserIds(group):
    return Member_Group.objects.filter(group = group).order_by('-join_date').values_list('user_id', flat=True)